import request from '@/utils/request'

/**
 * Python后端摄像头设备API接口
 * 用于AddCameraModal组件获取设备和通道信息
 * 
 * 🔄 智能数据源选择策略：
 * 1. 优先从Python后端数据库 (campus_twin.db) 读取摄像头数据
 * 2. 将摄像头数据转换为设备/通道格式供前端使用
 * 3. 如果数据库为空或查询失败，自动回退到WVP API
 * 
 * 📊 API路径映射：
 * - 摄像头列表: /api/v1/cameras/ (直接从数据库读取) → 转换为设备列表
 * - 摄像头筛选: /api/v1/cameras/?wvp_device_id={deviceId} → 转换为通道列表
 * - WVP设备列表: /api/wvp/devices (回退选项，从Java后端WVP获取)
 * - WVP设备通道: /api/wvp/devices/{deviceId}/channels (回退选项)
 * 
 * 💡 优势：
 * - 直接读取本地数据库，响应更快
 * - 支持离线工作（不依赖Java后端WVP）
 * - 自动回退机制确保兼容性
 * - 数据格式统一，前端无感知切换
 */

/**
 * 获取设备列表 - 优先从数据库读取摄像头，回退到WVP API
 * @param {Object} query 查询参数
 * @returns {Promise}
 */
export function listDevice(query = {}) {
  const params = {
    page: query.pageNum || query.page || 1,
    size: query.pageSize || query.size || 100,
    status: query.status,
    ai_enabled: query.ai_enabled
  }

  // 移除undefined值
  Object.keys(params).forEach(key => {
    if (params[key] === undefined || params[key] === '') {
      delete params[key]
    }
  })

  // 优先从WVP数据表读取设备数据
  return request({
    url: '/api/v1/cameras/wvp/devices',
    method: 'get',
    params: params
  }).then(response => {
    console.log('从WVP数据表获取设备数据:', response)

    // 如果WVP数据表有设备数据，直接返回
    if (response && response.success && response.data && response.data.rows) {
      return {
        code: 200,
        msg: response.message || '从WVP数据表查询成功',
        total: response.data.total || 0,
        rows: response.data.rows.map(device => ({
          deviceId: device.device_id,
          name: device.device_name || device.device_id,
          manufacturer: device.manufacturer || 'Unknown',
          model: device.model || 'Unknown',
          ip: device.ip || '',
          port: device.port || 5060,
          online: device.status === 'online',
          status: device.status || 'offline',
          channelCount: device.channel_count || 0,
          description: device.description || '',
          location: device.location || '',
          createTime: device.created_at,
          updateTime: device.updated_at
        }))
      }
    } else {
      console.log('WVP数据表无设备数据，尝试同步...')
      // 触发WVP数据同步
      return request({
        url: '/api/v1/cameras/wvp/sync',
        method: 'post'
      }).then(syncResponse => {
        if (syncResponse && syncResponse.success) {
          console.log('WVP数据同步成功，重新获取设备列表')
          // 同步成功后重新获取设备列表
          return request({
            url: '/api/v1/cameras/wvp/devices',
            method: 'get',
            params: params
          }).then(retryResponse => {
            if (retryResponse && retryResponse.success && retryResponse.data) {
              return {
                code: 200,
                msg: '同步后查询成功',
                total: retryResponse.data.total || 0,
                rows: (retryResponse.data.rows || []).map(device => ({
                  deviceId: device.device_id,
                  name: device.device_name || device.device_id,
                  manufacturer: device.manufacturer || 'Unknown',
                  model: device.model || 'Unknown',
                  ip: device.ip || '',
                  port: device.port || 5060,
                  online: device.status === 'online',
                  status: device.status || 'offline',
                  channelCount: device.channel_count || 0,
                  description: device.description || '',
                  location: device.location || '',
                  createTime: device.created_at,
                  updateTime: device.updated_at
                }))
              }
            } else {
              return {
                code: 200,
                msg: '查询成功但无数据',
                total: 0,
                rows: []
              }
            }
          })
        } else {
          return {
            code: 200,
            msg: '同步失败',
            total: 0,
            rows: []
          }
        }
      })
    }
  }).catch(error => {
    console.error('获取设备列表失败，尝试WVP API:', error)
    // 如果数据库查询失败，回退到WVP API
    return request({
      url: '/api/wvp/devices',
      method: 'get',
      params: { page: params.page, count: params.size }
    }).then(wvpResponse => {
      if (wvpResponse.success && wvpResponse.data) {
        return {
          code: 200,
          msg: '从WVP查询成功（数据库查询失败后回退）',
          total: wvpResponse.data.total || 0,
          rows: (wvpResponse.data.devices || []).map(formatDeviceResponse)
        }
      } else {
        throw formatErrorResponse(error)
      }
    }).catch(wvpError => {
      throw formatErrorResponse(error)
    })
  })
}

/**
 * 获取设备通道列表 - 优先从数据库读取摄像头，回退到WVP API
 * @param {Object} query 查询参数
 * @returns {Promise}
 */
export function listDeviceChannel(query = {}) {
  const { deviceId, ...otherParams } = query

  if (!deviceId) {
    return Promise.resolve({
      code: 200,
      msg: '查询成功',
      total: 0,
      rows: []
    })
  }

  // 从WVP通道数据表获取设备通道
  return request({
    url: `/api/v1/cameras/wvp/devices/${deviceId}/channels`,
    method: 'get',
    params: { page: 1, size: 100 }
  }).then(response => {
    console.log(`从WVP数据表获取设备${deviceId}的通道数据:`, response)

    // 如果WVP数据表有通道数据，直接返回
    if (response && response.success && response.data && response.data.rows) {
      const channels = response.data.rows.map(channel => ({
        channelId: channel.channel_id,
        deviceId: channel.device_id,
        name: channel.channel_name || channel.channel_id,
        status: channel.status === 'online' ? 'ON' : 'OFF',
        longitude: channel.longitude || 0,
        latitude: channel.latitude || 0,
        online: channel.status === 'online',
        description: channel.address || '',
        location: channel.address || '',
        manufacturer: channel.manufacturer || 'Unknown',
        model: channel.model || 'Unknown',
        ptzType: channel.ptz_type || 0,
        createTime: channel.created_at,
        updateTime: channel.updated_at
      }))

      return {
        code: 200,
        msg: '从WVP数据表查询通道成功',
        total: response.data.total || channels.length,
        rows: channels
      }
    } else {
      console.log(`WVP数据表无设备${deviceId}的通道数据`)
      return {
        code: 200,
        msg: '查询成功但无通道数据',
        total: 0,
        rows: []
      }
    }
  }).catch(error => {
    console.error('获取设备通道失败，尝试WVP API:', error)
    // 如果数据库查询失败，回退到WVP API
    return request({
      url: `/api/wvp/devices/${deviceId}/channels`,
      method: 'get'
    }).then(wvpResponse => {
      if (wvpResponse.success && wvpResponse.data) {
        return {
          code: 200,
          msg: '从WVP查询通道成功（数据库查询失败后回退）',
          total: wvpResponse.data.total || 0,
          rows: (wvpResponse.data.channels || []).map(formatChannelResponse)
        }
      } else {
        throw formatErrorResponse(error)
      }
    }).catch(wvpError => {
      throw formatErrorResponse(error)
    })
  })
}

/**
 * 获取设备详情 - 通过设备列表API获取特定设备
 * @param {string} deviceId 设备ID
 * @returns {Promise}
 */
export function getDeviceDetail(deviceId) {
  return request({
    url: '/api/wvp/devices',
    method: 'get',
    params: { page: 1, count: 1000 }
  }).then(response => {
    if (response.success && response.data && response.data.devices) {
      const device = response.data.devices.find(d => d.device_id === deviceId)
      if (device) {
        return {
          code: 200,
          msg: '查询成功',
          data: formatDeviceResponse(device)
        }
      } else {
        throw new Error(`设备 ${deviceId} 不存在`)
      }
    } else {
      throw new Error('获取设备列表失败')
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 获取通道详情 - 通过设备通道列表API获取特定通道
 * @param {string} deviceId 设备ID
 * @param {string} channelId 通道ID
 * @returns {Promise}
 */
export function getChannelDetail(deviceId, channelId) {
  return request({
    url: `/api/wvp/devices/${deviceId}/channels`,
    method: 'get'
  }).then(response => {
    if (response.success && response.data && response.data.channels) {
      const channel = response.data.channels.find(c => c.channel_id === channelId)
      if (channel) {
        return {
          code: 200,
          msg: '查询成功',
          data: formatChannelResponse(channel)
        }
      } else {
        throw new Error(`通道 ${channelId} 不存在`)
      }
    } else {
      throw new Error('获取通道列表失败')
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 获取设备在线状态 - 通过WVP状态API获取
 * @param {string} deviceId 设备ID
 * @returns {Promise}
 */
export function getDeviceStatus(deviceId) {
  return request({
    url: '/api/wvp/status',
    method: 'get'
  }).then(response => {
    // 从WVP状态中获取设备信息，这里简化处理
    return {
      code: 200,
      msg: '查询成功',
      data: {
        online: response.java_backend_wvp?.connected || false,
        lastHeartbeat: new Date().toISOString(),
        status: response.java_backend_wvp?.connected ? 'online' : 'offline'
      }
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 格式化设备响应数据 - 将Python后端WVP格式转换为前端兼容格式
 * @param {Object} device Python后端WVP设备数据
 * @returns {Object} 前端兼容格式的设备数据
 */
function formatDeviceResponse(device) {
  if (!device) return null

  return {
    // WVP兼容字段
    deviceId: device.device_id,
    name: device.device_name || device.name,
    manufacturer: device.manufacturer || 'Unknown',
    model: device.model || 'Unknown',
    firmware: device.firmware || 'Unknown',
    transport: device.transport || 'UDP',
    streamMode: device.stream_mode || 'UDP',
    ip: device.ip_address,
    port: device.port || 5060,
    hostAddress: device.ip_address,
    expires: device.expires || 3600,
    registerTime: device.register_time,
    keepaliveTime: device.keepalive_time,
    charset: device.charset || 'GB2312',
    subscribeCycleForCatalog: device.subscribe_cycle_catalog || 60,
    subscribeCycleForMobilePosition: device.subscribe_cycle_position || 5,
    mobilePositionSubmissionInterval: device.position_interval || 5,
    subscribeCycleForAlarm: device.subscribe_cycle_alarm || 60,
    ssrcCheck: device.ssrc_check || false,
    geoCoordSys: device.geo_coord_sys || 'WGS84',
    treeType: device.tree_type || 'CivilCode',
    online: device.status === 'online',

    // 扩展字段
    status: device.status || 'offline',
    channelCount: device.channels ? device.channels.length : 0,
    description: device.description || '',
    location: device.location || '',

    // 时间字段
    createTime: device.created_at,
    updateTime: device.updated_at,
    created_at: device.created_at,
    updated_at: device.updated_at
  }
}

/**
 * 格式化通道响应数据 - 将Python后端WVP格式转换为前端兼容格式
 * @param {Object} channel Python后端WVP通道数据
 * @returns {Object} 前端兼容格式的通道数据
 */
function formatChannelResponse(channel) {
  if (!channel) return null

  return {
    // WVP兼容字段
    channelId: channel.channel_id,
    deviceId: channel.device_id,
    name: channel.channel_name || channel.name,
    manufacturer: channel.manufacturer || 'Unknown',
    model: channel.model || 'Unknown',
    owner: channel.owner || '',
    civilCode: channel.civil_code || '',
    block: channel.block || '',
    address: channel.address || '',
    parental: channel.parental || 0,
    parentId: channel.parent_id || '',
    safetyWay: channel.safety_way || 0,
    registerWay: channel.register_way || 1,
    certNum: channel.cert_num || '',
    secrecy: channel.secrecy || 0,
    ipAddress: channel.ip_address,
    port: channel.port || 0,
    password: channel.password || '',
    status: channel.status || 'ON',
    longitude: channel.longitude || 0,
    latitude: channel.latitude || 0,
    ptzType: channel.ptz_type || 0,
    positionType: channel.position_type || 0,
    roomType: channel.room_type || 0,
    useType: channel.use_type || 0,
    supplyLightType: channel.supply_light_type || 0,
    directionType: channel.direction_type || 0,
    resolution: channel.resolution || '',
    businessGroupId: channel.business_group_id || '',
    downloadSpeed: channel.download_speed || '',
    svcSpaceSupportMode: channel.svc_space_support_mode || 0,
    svcTimeSupportMode: channel.svc_time_support_mode || 0,

    // 流媒体相关
    rtspUrl: channel.rtsp_url || '',
    rtmp_url: channel.rtmp_url || '',
    flv_url: channel.flv_url || '',
    hls_url: channel.hls_url || '',

    // 扩展字段
    online: channel.status === 'online',
    description: channel.description || '',
    location: channel.location || '',

    // 时间字段
    createTime: channel.created_at,
    updateTime: channel.updated_at,
    created_at: channel.created_at,
    updated_at: channel.updated_at
  }
}

/**
 * 将摄像头数据转换为设备列表格式
 * @param {Array} cameras 摄像头数组
 * @returns {Array} 设备数组
 */
function convertCamerasToDevices(cameras) {
  const deviceMap = new Map()

  cameras.forEach(camera => {
    const deviceId = camera.wvp_device_id
    if (!deviceId) return

    if (!deviceMap.has(deviceId)) {
      deviceMap.set(deviceId, {
        deviceId: deviceId,
        name: camera.name ? camera.name.split('_')[0] : deviceId,
        manufacturer: 'Unknown',
        model: 'Unknown',
        ip: '192.168.1.100', // 默认IP
        port: 5060,
        online: camera.status === 'online',
        status: camera.status || 'offline',
        channelCount: 0,
        description: `从摄像头数据生成的设备: ${deviceId}`,
        location: camera.location || '',
        createTime: camera.created_at,
        updateTime: camera.updated_at
      })
    }

    // 增加通道计数
    const device = deviceMap.get(deviceId)
    device.channelCount += 1
  })

  return Array.from(deviceMap.values())
}

/**
 * 将摄像头数据转换为通道格式
 * @param {Object} camera 摄像头数据
 * @returns {Object} 通道数据
 */
function convertCameraToChannel(camera) {
  return {
    channelId: camera.wvp_channel_id || camera.id,
    deviceId: camera.wvp_device_id,
    name: camera.name,
    status: camera.status === 'online' ? 'ON' : 'OFF',
    longitude: camera.longitude || 0,
    latitude: camera.latitude || 0,
    rtspUrl: camera.rtsp_url || '',
    online: camera.status === 'online',
    description: camera.description || '',
    location: camera.location || '',
    manufacturer: 'Unknown',
    model: 'Unknown',
    ptzType: 0,
    createTime: camera.created_at,
    updateTime: camera.updated_at
  }
}

/**
 * 格式化错误响应
 * @param {Object} error 错误对象
 * @returns {Object} 格式化的错误
 */
function formatErrorResponse(error) {
  if (error.response && error.response.data) {
    const errorData = error.response.data
    return {
      code: error.response.status || 500,
      msg: errorData.message || errorData.detail || '操作失败',
      data: null
    }
  }
  return {
    code: 500,
    msg: error.message || '网络错误',
    data: null
  }
}

/**
 * 重试机制装饰器
 * @param {Function} fn 要重试的函数
 * @param {number} maxRetries 最大重试次数
 * @param {number} delay 重试延迟
 * @returns {Function} 带重试机制的函数
 */
function withRetry(fn, maxRetries = 3, delay = 1000) {
  return async function (...args) {
    let lastError

    for (let i = 0; i < maxRetries; i++) {
      try {
        return await fn.apply(this, args)
      } catch (error) {
        lastError = error

        // 如果是客户端错误(4xx)，不重试
        if (error.response && error.response.status >= 400 && error.response.status < 500) {
          throw error
        }

        // 最后一次重试失败，抛出错误
        if (i === maxRetries - 1) {
          throw error
        }

        // 等待后重试
        await new Promise(resolve => setTimeout(resolve, delay * (i + 1)))
      }
    }

    throw lastError
  }
}

// 导出带重试机制的API函数
export const listDeviceWithRetry = withRetry(listDevice)
export const listDeviceChannelWithRetry = withRetry(listDeviceChannel)
export const getDeviceDetailWithRetry = withRetry(getDeviceDetail)
export const getChannelDetailWithRetry = withRetry(getChannelDetail)

// 设备数据模板
export const DeviceTemplate = {
  deviceId: '',
  name: '',
  manufacturer: '',
  model: '',
  ip: '',
  port: 5060,
  online: false,
  channelCount: 0,
  description: ''
}

// 通道数据模板
export const ChannelTemplate = {
  channelId: '',
  deviceId: '',
  name: '',
  status: 'ON',
  longitude: 0,
  latitude: 0,
  rtspUrl: '',
  online: false,
  description: ''
}